/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-leads
*
* @File name : LeadsController.java
*
* @Author : Administrator
*
* @Date : 2017年3月8日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月8日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.leads.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.dto.MQReceiveResult;
import org.marketing.common.dto.leads.InsuranceDto;
import org.marketing.common.dto.leads.ThreadcarDto;
import org.marketing.common.dto.leads.TmFixCodeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import org.marketing.common.dto.showroom.BrandExhibitionDto;
import org.marketing.common.dto.showroom.PackageSimpleDto;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.marketing.common.Response;
import com.yonyou.gmmc.service.leads.constant.LeadsConstant;
import com.yonyou.gmmc.service.leads.model.SaleInfo;
import com.yonyou.gmmc.service.leads.model.ThreadmqDto;
import com.yonyou.gmmc.service.leads.service.LeadsService;

/**
 * @author Administrator TODO description
 * @date 2017年3月8日
 */
@RestController
@RequestMapping(value = LeadsConstant.BASE_PATH + "/" + LeadsConstant.VERSION)
public class LeadsController {

    @Autowired
    private LeadsService leadsservice;
    private Logger       logger = Logger.getLogger(LeadsController.class);

    /**
     * 保存推荐购车
     * 
     * @author
     * @date 2017年4月13日
     * @param threadcardto
     * @return
     */
    @RequestMapping(value = "/saveThread", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveThread(@RequestBody ThreadcarDto threadcardto, HttpServletRequest request) {
        String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        Map<String, Object> map = leadsservice.saveThread(threadcardto, openId);
        return map;
    }

    
    /**
     * 獲取保險公司
     * 
     * @author Administrator TODO description
     * @date 2017年4月13日
     * @return
     */
    @RequestMapping(value = "/InsuranceMap", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<InsuranceDto> getInsuranceMap() {
        return leadsservice.getInsuranceMap();

    }
    

    /**
     * 获取字典表 推荐理由 code和name
     * 
     * @return
     */
    @RequestMapping(value = "/IscodeMap", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<TmFixCodeDto> getIscodeMap() {
        List<TmFixCodeDto> doList = leadsservice.getTscodename();
        return doList;

    }

    /**
     * 根据品牌code或查询所有品牌车系数据
     * 
     * @author QianKun
     * @date 2017年3月13日
     * @param brandCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/brands", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<BrandExhibitionDto> getBrandExhibitionData(@RequestParam("brandCode") String brandCode) throws Exception {
        List<BrandExhibitionDto> dtos = leadsservice.getBrandExhibitionData(brandCode);
        return dtos;
    }

    /**
     * @author LiuJun 根据车系code查询所有车型以及车型的配置-根据排量和变速箱类型
     * @date 2017年1月3日
     * @param seriesCode
     * @param dealerCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/displacement", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<PackageSimpleDto> getPackageDataByDisplacementAndGearboxType(@RequestParam("seriesCode") String seriesCode,
                                                                             @RequestParam("dealerCode") String dealerCode) throws Exception {

        List<PackageSimpleDto> pacakges = leadsservice.getPackageDataByDisplacementAndGearboxType(seriesCode,
                                                                                                  dealerCode);

        return pacakges;
    }

    /**
     * 通过推荐人 userid friendname recommendedcar 查找推荐时间
     * 
     * @param threadcardto
     * @return
     */
    @RequestMapping(value = "/Createtime", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<ThreadcarDto> getCreatetime(String friendphone, String recommendedcar, String dealerCode,
                                            HttpServletRequest request) {
        String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        List<ThreadcarDto> doList = leadsservice.getCreatetime(openId, friendphone, recommendedcar, dealerCode);
        return doList;

    }

    /**
     * 推荐购车接口
     * 
     * @param info
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/status", method = RequestMethod.POST)
    public MQReceiveResult saleInfo(@RequestBody IfMessage<List<SaleInfo>> info) throws Exception {
        MQReceiveResult message = new MQReceiveResult();
        logger.info("推送消息" + info);
        //代码扫描  1477
        List<SaleInfo> list1 = new ArrayList<SaleInfo>();
        List<SaleInfo> SaleInfoList = info.getIfData();
        for(SaleInfo saleInfo1 : SaleInfoList){
        	SaleInfo saleInfo2 = new SaleInfo();
        	saleInfo2.setRecommendNo(saleInfo1.getRecommendNo());
        	saleInfo2.setStatus(saleInfo1.getStatus());
        	list1.add(saleInfo2);
        }
        for (SaleInfo saleInfo : list1) {
            String recommendno = saleInfo.getRecommendNo();
            String status = saleInfo.getStatus();
//            logger.info("推送状态" + status);
            if ("1".equals(status)) {
                logger.info("成功");
                // 更新recommendno_status为1
                leadsservice.updateStatus(recommendno, status);
                // 判断该线索是否超过1年
                if (leadsservice.checkTime(recommendno)) {
                    logger.info("该线索未超过1年");
                    // 判断是否车主
                    if (leadsservice.checkIsCarOwner(recommendno)) {
                        // 车主,加350分
                        leadsservice.getThreadmq(recommendno);
                    } else {
                        // 会员
                        // 查询该推荐单的线索状态
                        String thread_Status = leadsservice.selectThreadStatus(recommendno);
                        if ("2".equals(thread_Status)) {
                            // 新线索,加350分
                            leadsservice.getThreadmq(recommendno);
                        } else if ("3".equals(thread_Status)) {
                            // 重复线索，不加分
                            logger.info("重复线索，不加分");
                        } else {
                            // 无状态，不处理
                            logger.info("无状态，不处理");
                        }
                    }
                } else {
                    logger.info("该线索已超过一年");
                    // 状态更新为已过期(6.已超过1年)
                    int i = leadsservice.updateThreadStatus("6", recommendno);
                    logger.info("更新数——————" + i);
                }
            } else if ("2".equals(status)) {
                logger.info("新线索");
                // 更新推荐单线索状态(THREAD_STATUS)
                int i = leadsservice.updateThreadStatus(status, recommendno);
                logger.info("更新数——————" + i);
                if (leadsservice.checkIsCarOwner(recommendno)) {
                    // 车主,加15分
                    leadsservice.sendLeadsPointsToMq(recommendno);
                } else {
                    // 会员,不加分
                }
            } else if ("3".equals(status)) {
                logger.info("重复线索");
                // 更新推荐单线索状态(THREAD_STATUS)
                int i = leadsservice.updateThreadStatus(status, recommendno);
                logger.info("更新数——————" + i);
            } else if ("4".equals(status)) {
                logger.info("无效线索");
                // 更新推荐单线索状态(THREAD_STATUS)
                int i = leadsservice.updateThreadStatus(status, recommendno);
                logger.info("更新数——————" + i);
                // if (leadsservice.checkLead(recommendno)) {
                // //发放过积分的线索，发送事件，扣除15分
                // leadsservice.getThreadInvalidmq(recommendno);
                // logger.info("无效线索，发放过积分，扣分");
                // }else{
                // //没有发过积分，不扣分
                // logger.info("无效线索，但没有发放积分或已扣过积分，不扣分");
                // }
            } else if ("5".equals(status)) {
                logger.info("退车线索");
                int i = leadsservice.updateThreadStatus(status, recommendno);
                logger.info("更新数——————" + i);

                leadsservice.backThread(recommendno);
            } else {
                logger.info("失败");
                // 更新线索状态
                leadsservice.updateStatus(recommendno, status);
            }

            // if ("1".equals(status)) {
            // leadsservice.getThreadmq(recommendno);
            // logger.info("推送结束。。。。。");
            // }
        }
        message.setResult("200");
        message.setMessage("业务完成");// 返回的消息
        return message;

    }

    /**
     * 测试使用
     * 
     * @param recommendno
     * @param status
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public void updateStatus(String recommendno, String status) {
        leadsservice.updateStatus(recommendno, status);
    }

    /**
     * 测试使用
     * 
     * @param recommendno
     * @return
     */
    @RequestMapping(value = "/Threadmq", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<ThreadmqDto> getThreadmq(String recommendno) {
        List<ThreadmqDto> doList = leadsservice.getThreadmq(recommendno);
        return doList;

    }

    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public void getThread(ThreadcarDto threadcardto) throws Exception {
    	//代码扫描  1478
    	ThreadcarDto threadcardto1 = new ThreadcarDto();
    	threadcardto1.setThreadId(threadcardto.getThreadId());
    	threadcardto1.setFriendname(threadcardto.getFriendname());
    	threadcardto1.setFriendphone(threadcardto.getFriendphone());
    	threadcardto1.setRecommendedcar(threadcardto.getRecommendedcar());
    	threadcardto1.setRecommendedstore(threadcardto.getRecommendedstore());
    	threadcardto1.setRecommendedreasons(threadcardto.getRecommendedreasons());
    	threadcardto1.setUsername(threadcardto.getUsername());
    	threadcardto1.setUserphone(threadcardto.getUserphone());
        leadsservice.sendMessage2MQ(threadcardto1);

    }

    /**
     * 判断朋友手机号和推荐店是否唯一
     * 
     * @param friendphone
     * @param dealerCode
     * @return
     */
    @RequestMapping(value = "/ThreadPhone", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<ThreadcarDto> getThreadPhone(String friendphone, String dealerCode) {
        List<ThreadcarDto> doList = leadsservice.getThreadPhone(friendphone, dealerCode);
        return doList;

    }

    @RequestMapping(value = "/taskThread", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> Thread() {
        Map<String, Object> map = leadsservice.Thread();
        return map;
    }

    @RequestMapping(value = "/myThread", method = RequestMethod.GET)
    public Response<List<ThreadcarDto>> myThread(HttpServletRequest request) throws Exception {
        try {
            String openId = request.getHeader(CommonConstant.HEADER_OPENID);
//            String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
            List<ThreadcarDto> result = leadsservice.myThread(openId);
            return new Response<List<ThreadcarDto>>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
        } catch (Exception e) {
            logger.error("查询发生异常", e);
            return new Response<List<ThreadcarDto>>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }

}
